$(function(){
    //初始化
    initQuestions();
    var set = getExamSet();
    resetTime(set.time-1);
    $(".page").bind("click",function(){ $(".pageBoxBg").toggle();});
    $(".page").click(function(){
        $(".Mbottom").toggleClass("datiBottom");
    });
    $(document).click(function(e){
        var hasDatiBottom = $(".Mbottom").hasClass("datiBottom");
        if( $(e.target).closest('.pageBox').length == 0 && $(e.target).closest('.Mbottom').length == 0 && hasDatiBottom){
            $(".page").click();
        }
    });
    //up, right, down, left为四个回调函数，分别处理上下左右的滑动事件
    EventUtil.listenTouchDirection(document,true,null,left,null,next);

    /*** 记录选项，记录选择，改变选项卡状态*/
    $("body").on("click","input[name='dx']",function () {
        var currentNum = parseInt($("#currentPage").text())-1;
        var hisOption = "";
        if(answer[currentNum].questionType == 2){
            $("input[name='dx']:checked").each(function(i){
                hisOption += ","+$(this).val();
            });
            hisOption = hisOption.substr(1);
        }else{
            hisOption = $(this).val();
        }
        answer[currentNum].hisOption = hisOption;
        if(hisOption == answer[currentNum].questionAnswer){
            answer[currentNum].isPass = 1;
        }else{
            answer[currentNum].isPass = 0;
        }
        $(".timuBox>li").eq(currentNum).addClass("actTi");
        if(hisOption==""){
            $(".timuBox>li").eq(currentNum).removeClass("actTi");
        }
        if(answer[currentNum].questionType != 2){
            setTimeout(function(){
                setQuestion(currentNum+1);
            },500);
        }
    });

    /*** 点击选项卡切换题目*/
    $("body").on("click",".timuBox>li",function(){
        var n = parseInt($(this).text()) - 1;
        setQuestion(n);
    });

    /*** 提交*/
    $(".jiaojuanBtn").click(function(){
        var submitData = {};
        //验证是否有没选的
        var find = $(".timuBox").find("li");
        var flag = 0;
        for(var i=0;i<find.length;i++){
            if(!$(".timuBox").find("li").eq(i).hasClass("actTi")){
                flag++;
            }
        }
        if(flag>0){
            layer.open({
                content: '您还有'+flag+'道题未答'
                ,btn: '继续答题'
            });
            return;
        }
        layer.open({
            content: '您确定要提交么？'
            , btn: ['确定提交', '继续答题']
            , yes: function (index) {
                //是否通过
                var passCount = set.passCount;
                var pass = 0;
                for(var i in answer){
                    if(answer.isPass == 1 ){
                        pass += 1;
                    }
                }
                if(pass>=passCount){
                    submitData['isPass'] = 1;
                }else{
                    submitData['isPass'] = 0;
                }
                //答题时间
                var examSet = getExamSet();
                submitData['useTime'] = getUseTime(examSet.time,$("#downTime").html());
                submitData['answer'] = answer;
                console.log(JSON.stringify(submitData));
                window.localStorage.setItem("specialAnswerItem",JSON.stringify(submitData));
                location.href = "/mp/train/changePage?url=/mp/special-result";
            }
        });
    });
    /*** 多选题 确认答案*/
    $(".confirm-btn").click(function () {
        var currentPage = parseInt($("#currentPage").text());
        var total = parseInt($("#total").text());
        if(currentPage == total){
            $(".jiaojuanBtn").click();
            return;
        }
        setTimeout(function () {
            next();
        },500);
    })
});
function initQuestions() {
    $.ajax({
        url:"/mp/question/getSpecialQuestion",
        async:false,
        dataType:"json",
        success:function(result){
            if(result.data.length==0){
                $("body").html('<img src="images/nothing.png" style="width: 100%;position: fixed;top: 23%">');
                return
            }
            answer = result.data;
        }
    });

    var length = answer.length;
    $("#total").text(length);
    var totalHtml = "";
    for(var i=1;i<= length;i++){
        totalHtml += '<li class="iphoneModel">'+i+'</li>';
    }
    $(".timuBox").html(totalHtml);
    setQuestion(0);
}
function left(){
    var currentPage = parseInt($("#currentPage").text());
    if((currentPage)-1>0){
        setQuestion(currentPage-2);
    }
}
function next(){
    var currentPage = parseInt($("#currentPage").text());
    var total = parseInt($("#total").text());
    setQuestion(currentPage);
}
/*** 将题目填充html* @param n 第n题*/
function setQuestion(n) {
    var optionArr = ["A","B","C","D","E","F"];
    var question = answer[n];
    var questionArr = formatArr(question);
    var headImg = "";
    var html = "";
    var optionsHtml = "";
    var collections = JSON.parse(window.localStorage.getItem("collectionItem"));
    $("#collection").html('<img src="images/sc.png">收藏');
    for(var i in collections){
        if(collections[i] == question.questionId){
            $("#collection").html('<img src="images/qx.png">取消');
        }
    }
    $("#questionId").val(question.questionId);
    //多选
    if(question.questionType == 2){//多选
        headImg = "/mp/images/duoxuan.png";
    }else if(question.questionType == 0){//判断
        headImg = "/mp/images/pd.png";
    }else{
        headImg = "/mp/images/dx.png";
    }
    if(question.questionType == 2){//多选
        var flag = false;
        var hisOption = question.hisOption;
        var split;
        if(hisOption){
            split = hisOption.split(",");
            console.log(split);
            flag = true;
        }
        $(".confirm-btn").show();
        for(var i in questionArr){
            if(questionArr[i].trim()!="" && questionArr[i]!=null){
                if(flag && split.indexOf(optionArr[i])>-1){
                    optionsHtml += '<div class="popCheckOne ">'+
                            '<input type="checkbox" value="'+optionArr[i]+'" name="dx" id="'+optionArr[i]+'" checked>'+
                            '<label  for="'+optionArr[i]+'" class="col3">'+optionArr[i]+"."+questionArr[i]+'</label>'+
                        '</div>';
                }else{
                    optionsHtml += '<div class="popCheckOne">'+
                            '<input type="checkbox" value="'+optionArr[i]+'" name="dx" id="'+optionArr[i]+'">'+
                            '<label  for="'+optionArr[i]+'" class="col3">'+optionArr[i]+"."+questionArr[i]+'</label>'+
                        '</div>';
                }
            }
        }
    }else{
        $(".confirm-btn").hide();
        optionsHtml += '<div class="singleRadio padd20">';
        for(var i in questionArr){
            if(questionArr[i].trim()!="" && questionArr[i]!=null){
                if(question.hisOption == optionArr[i]){
                    optionsHtml += '<div class="radios">'+
                        '<input type="radio" value="'+optionArr[i]+'" name="dx" id="'+optionArr[i]+'" checked>'+
                        '<label class="radioStyle" for="'+optionArr[i]+'">'+optionArr[i]+"."+questionArr[i]+'</label>'+
                        '</div>';
                }else{
                    optionsHtml += '<div class="radios">'+
                        '<input type="radio" value="'+optionArr[i]+'" name="dx" id="'+optionArr[i]+'">'+
                        '<label class="radioStyle" for="'+optionArr[i]+'">'+optionArr[i]+"."+questionArr[i]+'</label>'+
                        '</div>';
                }
            }
        }
        optionsHtml += '</div>';
    }
    html += '<p class="fsSmall30 col3 topicItem padd20"><img src="'+headImg+'" alt="" class="dxIcon">'+question.questionContent+'</p>'+optionsHtml;
    $(".content").html(html);
    $("#currentPage").text(n+1);
    window.scrollTo(0,0);
    $("#content").hide();
    $("#content").fadeIn(900);
}

function formatArr(question) {
    var arr = [];
    arr.push(question.optionA);
    arr.push(question.optionB);
    arr.push(question.optionC);
    arr.push(question.optionD);
    arr.push(question.optionE);
    arr.push(question.optionF);
    return arr;
}

/*** 获取考试设置*/
function getExamSet(){
    var set = [];
    $.ajax({
        url:"/mp/question/getSpecialSet",
        async:false,
        type:"get",
        dataType:"json",
        success:function (result) {
            set = result.data;
        }
    });
    return set;
}

//倒计时
function resetTime(time){
    var timer=null;
    var m=time;
    var s=60;
    function countDown(){
        s--;
        if(s==0 && m>0){
            m--;
            s=60;
        }
        if(m==0 && s==0){
            m='00';
            s='00';
            clearInterval(timer);
            countDownSubmit();
        }
        var min = m>9?m:"0"+m;
        var second = s>9?s:"0"+s;
        /*$(".countDownTime").html('<img src="/mp/images/time.png" class="timeIcon"/>'+min+':'+second);*/
        $("#downTime").html(min+':'+second);
    }
    timer=setInterval(countDown,1000);
}

function countDownSubmit(){
    var submitData = {};
    //是否通过
    var examSet = getExamSet();
    var passCount = examSet.passCount;
    var pass = 0;
    for(var i in answer){
        if(answer.isPass == 1 ){
            pass += 1;
        }
    }
    if(pass>=passCount){
        submitData['isPass'] = 1;
    }else{
        submitData['isPass'] = 0;
    }
    //答题时间
    submitData['useTime'] =getUseTime(examSet.time,$("#downTime").html());
    submitData['answer'] = answer;
    console.log(JSON.stringify(submitData));
    window.localStorage.setItem("specialAnswerItem",JSON.stringify(submitData));
    location.href = "/mp/train/changePage?url=/mp/special-result";
}
